package com.hippoDocker.security.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hippoDocker.security.dao.UmsMemberDao;
import com.hippoDocker.security.dao.UmsPermissionDao;
import com.hippoDocker.security.entity.UmsMember;
import com.hippoDocker.security.pojo.dto.LoginUserDTO;
import com.hippoDocker.security.pojo.dto.UmsMemberDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName UserDetailsServiceImpl
 * @Description TODO 重写spring-security用户校验
 * @Author tangxl
 * @Date 2022/7/26 10:51
 **/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UmsMemberDao umsMemberDao;
    @Autowired
    private UmsPermissionDao umsPermissionDao;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
        LambdaQueryWrapper<UmsMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UmsMember ::getUsername,username);
        UmsMember umsMember = umsMemberDao.selectOne(queryWrapper);
        //用户信息校验
        if (umsMember == null) {
            throw new UsernameNotFoundException("用户名或者密码错误！");
        }
        //TODO 数据库查询对应权限信息  RBAC权限模型
        List<String> permissionList = umsPermissionDao.selectValuesByUserId(umsMember.getId());
        List<String> list = new ArrayList<>(permissionList);
        //封装UserDetails返回
        LoginUserDTO loginUserDTO = new LoginUserDTO(Convert.convert(UmsMemberDTO.class,umsMember),list);
        return loginUserDTO;
    }

}
